package JUC.第02章_Future;

import java.util.concurrent.*;

public class D6_CompletableFuture选取速度快的 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);//固定线程

        CompletableFuture<Integer> cf1 =
                CompletableFuture.supplyAsync(() -> {
                    int result = ThreadLocalRandom.current().nextInt(1000);//随机获取[0-9]
                    try { TimeUnit.MILLISECONDS.sleep(result); }catch (Exception e){e.printStackTrace();}
                    System.out.println("cf1--------------" + result);
                    return result;
                },executorService);
        CompletableFuture<Integer> cf2 =
                CompletableFuture.supplyAsync(() -> {
                    int result = ThreadLocalRandom.current().nextInt(1000);//随机获取[0-9]
                    try { TimeUnit.MILLISECONDS.sleep(result); }catch (Exception e){e.printStackTrace();}
                    System.out.println("cf2--------------" + result);
                    return result;
                    },executorService);

        CompletableFuture<Integer> cf0 = cf1.applyToEither(cf2, (f) -> {
            return f;
        });// applyToEither 谁速度快  用哪个

        System.out.println("最快的：" + cf0.join());

        executorService.shutdown();
    }
}
